package com.kaifamiao.config;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;

@WebServlet( name = "configAnnotation" ,
             urlPatterns = "/config/anno" ,
             initParams = { @WebInitParam( name="encoding" , value = "UTF-8" ) ,
                            @WebInitParam( name="time" , value = "2021-12-13" ) } )
public class ConfigAnnotationServlet extends HttpServlet {

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        // 当前类继承了 HttpServlet 类，HttpServlet 类继承了 GenericServlet ， GenericServlet 实现了 Servlet 接口
        // ServletConfig config = this.getServletConfig();
        // Enumeration<String> initParamNames = config.getInitParameterNames();

        // 当前类继承了 HttpServlet 类，HttpServlet 类继承了 GenericServlet ， GenericServlet 实现了 ServletConfig 接口
        Enumeration<String> initParamNames = this.getInitParameterNames();
        Iterator<String> itor = initParamNames.asIterator(); // Java 9 提供的方法

        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html" );
        PrintWriter out = response.getWriter();

        out.println( "<table>" );
        out.println( "<tr>");
        // 获得 servlet 的名称 ( 即通过 <servlet-name> 指定的值 或 @WebServlet 的 name 属性指定的值 )
        out.println( "<td colspan=\"2\">" + this.getServletName() + "</td>");
        out.println( "</tr>");
        while( itor.hasNext() ){
            // 获取单个 初始化参数名称
            String paramName = itor.next();
            // 根据 初始化参数 的 名称 获得初始化参数的值
            String paramValue = this.getInitParameter( paramName );
            out.println( "<tr>");
            out.println( "<td>" + paramName + "</td>");
            out.println( "<td>" + paramValue + "</td>");
            out.println( "</tr>");
        }
        out.println( "</table>" );


    }
}
